package com.ywu.sentinel.standard.service;

import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.entity.PageList;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.page.PageService;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.TimerIdGenerateUtil;
import com.ywu.sentinel.sdk.dto.*;
import com.ywu.sentinel.standard.data.YwuBlowRuleRepository;
import com.ywu.sentinel.standard.data.YwuFlowRuleRepository;
import com.ywu.sentinel.standard.data.YwuHotRuleRepository;
import com.ywu.sentinel.standard.data.YwuSystemRuleRepository;
import com.ywu.sentinel.standard.entity.YwuBlowRuleEntity;
import com.ywu.sentinel.standard.entity.YwuFlowRuleEntity;
import com.ywu.sentinel.standard.entity.YwuHotRuleEntity;
import com.ywu.sentinel.standard.entity.YwuSystemRuleEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @ClassName YwuFlowRuleService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/4/14 18:49
 * @Version 1.0
 **/
@Service
@Slf4j
public class YwuFlowRuleService {
    @Autowired
    private YwuFlowRuleRepository repository;

    @Autowired
    private YwuBlowRuleRepository blowRuleRepository;

    @Autowired
    private YwuHotRuleRepository hotRuleRepository;

    @Autowired
    private YwuSystemRuleRepository systemRuleRepository;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    private static final String FLOW_RULE_CREATE_URL = "/ywu/sentinel/rule/sdk/sentinel.flow.rule.create";

    private static final String FLOW_RULE_DELETE_URL = "/ywu/sentinel/rule/sdk/sentinel.flow.rule.delete";

    private static final String FLOW_RULE_UPDATE_URL = "/ywu/sentinel/rule/sdk/sentinel.flow.rule.update";

    private static final String BLOW_RULE_CREATE_URL = "/ywu/sentinel/rule/sdk/sentinel.blow.rule.create";

    private static final String BLOW_RULE_DELETE_URL = "/ywu/sentinel/rule/sdk/sentinel.blow.rule.delete";

    private static final String BLOW_RULE_UPDATE_URL = "/ywu/sentinel/rule/sdk/sentinel.blow.rule.update";

    private static final String HOT_RULE_CREATE_URL = "/ywu/sentinel/rule/sdk/sentinel.hot.rule.create";

    private static final String HOT_RULE_DELETE_URL = "/ywu/sentinel/rule/sdk/sentinel.hot.rule.delete";

    private static final String HOT_RULE_UPDATE_URL = "/ywu/sentinel/rule/sdk/sentinel.hot.rule.update";

    private static final String SYSTEM_RULE_CREATE_URL = "/ywu/sentinel/rule/sdk/sentinel.system.rule.create";

    private static final String SYSTEM_RULE_DELETE_URL = "/ywu/sentinel/rule/sdk/sentinel.system.rule.delete";

    private static final String SYSTEM_RULE_UPDATE_URL = "/ywu/sentinel/rule/sdk/sentinel.system.rule.update";

    private static final String COMMON_RULE_LIST_URL = "/ywu/sentinel/rule/sdk/sentinel.common.rule.list.info";

    /**
    * @Author GroundDemo
    * @Description 添加流控规则
    * @Date 18:51 2025/4/14
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> createFlowRule(YwuFlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 构建对象
        YwuFlowRuleEntity entity = new YwuFlowRuleEntity();
        BeanUtils.copyProperties(ruleDto, entity);
        entity.setId(TimerIdGenerateUtil.nextId());
        entity.setLimitApp("default");
        entity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        entity.createInfo(currentContext.getYwuContextUser().getUserAccount());
        // 调用微服务添加流控规则
        ruleDto.setId(entity.getId());
        doRestTemplate(ruleDto.getApp(), FLOW_RULE_CREATE_URL, ruleDto);
        // 插入数据
        repository.insert(entity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除流控规则
    * @Date 19:07 2025/4/14
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> deleteFlowRule(YwuFlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuFlowRuleEntity search = new YwuFlowRuleEntity();
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        search.setId(ruleDto.getId());
        YwuFlowRuleEntity queryEntity = repository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用微服务删除流控规则
        doRestTemplate(ruleDto.getApp(), FLOW_RULE_DELETE_URL, ruleDto);
        // 删除数据
        YwuFlowRuleEntity delete = new YwuFlowRuleEntity();
        delete.setId(ruleDto.getId());
        repository.delete(delete);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询流控规则列表
    * @Date 19:10 2025/4/14
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryFlowRuleList(YwuFlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        List<YwuFlowRuleEntity> queryList = repository.queryList(ruleDto);
        return CommonResult.success(queryList);
    }

    /**
    * @Author GroundDemo
    * @Description 执行请求
    * @Date 8:54 2025/4/15
    * @Param [serviceName, url, requestBody]
    * @return void
    **/
    private void doRestTemplate(String serviceName, String url, Object requestBody) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        // 遍历每一个实例，进行接口调用
        for (ServiceInstance instance : instances) {
            String host = instance.getHost();
            int port = instance.getPort();
            String realUrl = "http://" + host + ":" + port + url;
            log.debug("url ======= {}", realUrl);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> httpEntity = new HttpEntity<>(requestBody, headers);
            CommonResult commonResult = restTemplate.postForObject(realUrl, httpEntity, CommonResult.class);
            if (commonResult == null || !commonResult.getCode().equals("200")) {
                throw new YwuRuntimeException("rule create error");
            }
            log.debug("common res {}", GsonUtils.serialize(commonResult));
        }
    }

    /**
    * @Author GroundDemo
    * @Description 添加熔断规则
    * @Date 9:19 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> createBlowRule(YwuBlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 构建对象
        YwuBlowRuleEntity entity = new YwuBlowRuleEntity();
        BeanUtils.copyProperties(ruleDto, entity);
        entity.setId(TimerIdGenerateUtil.nextId());
        entity.setLimitApp("default");
        entity.createInfo(currentContext.getYwuContextUser().getUserAccount());
        entity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        // 调用微服务添加流控规则
        ruleDto.setId(entity.getId());
        doRestTemplate(ruleDto.getApp(), BLOW_RULE_CREATE_URL, ruleDto);
        // 插入数据
        blowRuleRepository.insert(entity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除熔断规则
    * @Date 9:20 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> deleteBlowRule(YwuBlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuBlowRuleEntity search = new YwuBlowRuleEntity();
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        search.setId(ruleDto.getId());
        YwuBlowRuleEntity queryEntity = blowRuleRepository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用微服务删除流控规则
        doRestTemplate(ruleDto.getApp(), BLOW_RULE_DELETE_URL, ruleDto);
        // 删除数据
        YwuBlowRuleEntity delete = new YwuBlowRuleEntity();
        delete.setId(ruleDto.getId());
        blowRuleRepository.delete(delete);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询熔断规则列表
    * @Date 9:20 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryBlowRuleList(YwuBlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        List<YwuBlowRuleEntity> queryList = blowRuleRepository.queryList(ruleDto);
        return CommonResult.success(queryList);
    }

    /**
    * @Author GroundDemo
    * @Description 添加热点规则
    * @Date 11:06 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> createHotRule(YwuHotRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 构建对象
        YwuHotRuleEntity entity = new YwuHotRuleEntity();
        BeanUtils.copyProperties(ruleDto, entity);
        entity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        entity.setId(TimerIdGenerateUtil.nextId());
        entity.setLimitApp("default");
        entity.createInfo(currentContext.getYwuContextUser().getUserAccount());
        entity.setParamFlowItemListStr(GsonUtils.serialize(entity.getParamFlowItemList()));
        // 调用微服务添加流控规则
        ruleDto.setId(entity.getId());
        doRestTemplate(ruleDto.getApp(), HOT_RULE_CREATE_URL, ruleDto);
        // 插入数据
        hotRuleRepository.insert(entity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除热点规则
    * @Date 11:07 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> deleteHotRule(YwuHotRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuHotRuleEntity search = new YwuHotRuleEntity();
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        search.setId(ruleDto.getId());
        YwuHotRuleEntity queryEntity = hotRuleRepository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用微服务删除流控规则
        doRestTemplate(ruleDto.getApp(), HOT_RULE_DELETE_URL, ruleDto);
        // 删除数据
        YwuHotRuleEntity delete = new YwuHotRuleEntity();
        delete.setId(ruleDto.getId());
        hotRuleRepository.delete(delete);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询热点规则列表
    * @Date 11:07 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryHotRuleList(YwuHotRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        List<YwuHotRuleEntity> queryList = hotRuleRepository.queryList(ruleDto);
        queryList.forEach(res -> {
            res.setParamFlowItemList(GsonUtils.deserializeList(res.getParamFlowItemListStr(), YwuParamItemDto.class));
        });
        return CommonResult.success(queryList);
    }

    /**
    * @Author GroundDemo
    * @Description 查询当前微服务内部的所有热点规则
    * @Date 11:59 2025/4/15
    * @Param [serviceName]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryAllRuleInnerList(String serviceName) {
        // 获取所有实例
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        HashMap<String, Object> res = new HashMap<>();
        for (ServiceInstance instance : instances) {
            int port = instance.getPort();
            String host = instance.getHost();
            String realUrl = "http://" + host + ":" + port + COMMON_RULE_LIST_URL;
            log.debug("queryAllRuleInnerList url ======= {}", realUrl);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> httpEntity = new HttpEntity<>(null, headers);
            CommonResult commonResult = restTemplate.postForObject(realUrl, httpEntity, CommonResult.class);
            if (commonResult == null || !commonResult.getCode().equals("200")) {
                throw new YwuRuntimeException("rule query error");
            }
            Map<String, Object> resMap = (Map<String, Object>) commonResult.getData();
            res.put(host + ":" + port, resMap);
        }
        return CommonResult.success(res);
    }

    /**
    * @Author GroundDemo
    * @Description 分页查询流控列表
    * @Date 12:18 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryFlowRulePageList(YwuFlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        PageService.execPageStartAndEnd(ruleDto.getPageInfo());
        PageList<YwuFlowRuleEntity> pageListRes = new PageList<>();
        pageListRes.setPageIndex(ruleDto.getPageInfo().getPageIndex());
        pageListRes.setPageSize(ruleDto.getPageInfo().getPageSize());
        // 查询数量
        int count = repository.queryListCount(ruleDto);
        pageListRes.setRecordCount(count);
        if (count == 0) {
            pageListRes.setDataList(new ArrayList<>());
            return CommonResult.success(pageListRes);
        }
        // 查询列表
        List<YwuFlowRuleEntity> ywuFlowRuleEntities = repository.queryPageList(ruleDto);
        pageListRes.setDataList(ywuFlowRuleEntities);
        return CommonResult.success(pageListRes);
    }

    /**
    * @Author GroundDemo
    * @Description 修改规则信息
    * @Date 13:37 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    @Transactional
    public CommonResult<Object> updateFlowRule(YwuFlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuFlowRuleEntity search = new YwuFlowRuleEntity();
        search.setId(ruleDto.getId());
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        YwuFlowRuleEntity queryEntity = repository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用接口进行修改
        doRestTemplate(ruleDto.getApp(), FLOW_RULE_UPDATE_URL, ruleDto);
        // 修改数据
        YwuFlowRuleEntity update = new YwuFlowRuleEntity();
        BeanUtils.copyProperties(ruleDto, update);
        update.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        repository.update(update);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 修改熔断规则
    * @Date 13:48 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateBlowRule(YwuBlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuBlowRuleEntity search = new YwuBlowRuleEntity();
        search.setId(ruleDto.getId());
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        YwuBlowRuleEntity queryEntity = blowRuleRepository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用接口进行修改
        doRestTemplate(ruleDto.getApp(), BLOW_RULE_UPDATE_URL, ruleDto);
        // 修改数据
        YwuBlowRuleEntity update = new YwuBlowRuleEntity();
        BeanUtils.copyProperties(ruleDto, update);
        update.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        blowRuleRepository.update(update);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 修改热点规则
    * @Date 13:52 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateHotRule(YwuHotRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuHotRuleEntity search = new YwuHotRuleEntity();
        search.setId(ruleDto.getId());
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        YwuHotRuleEntity queryEntity = hotRuleRepository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用接口进行修改
        doRestTemplate(ruleDto.getApp(), HOT_RULE_UPDATE_URL, ruleDto);
        // 修改数据
        YwuHotRuleEntity update = new YwuHotRuleEntity();
        BeanUtils.copyProperties(ruleDto, update);
        update.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        update.setParamFlowItemListStr(GsonUtils.serialize(update.getParamFlowItemList()));
        hotRuleRepository.update(update);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 分页查询
    * @Date 14:30 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryBlowRulePageList(YwuBlowRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        PageService.execPageStartAndEnd(ruleDto.getPageInfo());
        PageList<YwuBlowRuleEntity> pageListRes = new PageList<>();
        pageListRes.setPageSize(ruleDto.getPageInfo().getPageSize());
        pageListRes.setPageIndex(ruleDto.getPageInfo().getPageIndex());
        // 查询数量
        int count = blowRuleRepository.queryListCount(ruleDto);
        pageListRes.setRecordCount(count);
        if (count == 0) {
            log.debug("queryBlowRulePageList empty");
            pageListRes.setDataList(new ArrayList<>());
            return CommonResult.success(pageListRes);
        }
        // 查询列表
        List<YwuBlowRuleEntity> ywuBlowRuleEntityList = blowRuleRepository.queryPageList(ruleDto);
        pageListRes.setDataList(ywuBlowRuleEntityList);
        return CommonResult.success(pageListRes);
    }

    /**
    * @Author GroundDemo
    * @Description 分页查询
    * @Date 14:35 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryHotRulePageList(YwuHotRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        PageService.execPageStartAndEnd(ruleDto.getPageInfo());
        PageList<YwuHotRuleEntity> pageListRes = new PageList<>();
        pageListRes.setPageSize(ruleDto.getPageInfo().getPageSize());
        pageListRes.setPageIndex(ruleDto.getPageInfo().getPageIndex());
        // 查询数量
        int count = hotRuleRepository.queryListCount(ruleDto);
        pageListRes.setRecordCount(count);
        if (count == 0) {
            log.debug("queryHotRulePageList empty");
            pageListRes.setDataList(new ArrayList<>());
            return CommonResult.success(pageListRes);
        }
        // 查询列表
        List<YwuHotRuleEntity> ywuFlowRuleEntities = hotRuleRepository.queryPageList(ruleDto);
        ywuFlowRuleEntities.forEach(res -> {
            res.setParamFlowItemList(GsonUtils.deserializeList(res.getParamFlowItemListStr(), YwuParamItemDto.class));
        });
        pageListRes.setDataList(ywuFlowRuleEntities);
        return CommonResult.success(pageListRes);
    }

    /**
    * @Author GroundDemo
    * @Description 创建系统规则
    * @Date 19:52 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> createSystemRule(YwuSystemRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 判断当前规则类型是否存在（一个微服务一种类型只能有一个）
        YwuSystemRuleEntity search = new YwuSystemRuleEntity();
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        search.setApp(ruleDto.getApp());
        search.setType(ruleDto.getType());
        YwuSystemRuleEntity queryEntity = systemRuleRepository.getEntity(search);
        if (Objects.nonNull(queryEntity)) {
            // 当前类型已经存在
            return CommonResult.error().setMessage("current type has exists");
        }
        // 构建对象
        YwuSystemRuleEntity entity = new YwuSystemRuleEntity();
        BeanUtils.copyProperties(ruleDto, entity);
        entity.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        entity.setId(TimerIdGenerateUtil.nextId());
        entity.createInfo(currentContext.getYwuContextUser().getUserAccount());
        // 调用微服务添加流控规则
        ruleDto.setId(entity.getId());
        doRestTemplate(ruleDto.getApp(), SYSTEM_RULE_CREATE_URL, ruleDto);
        // 插入数据
        systemRuleRepository.insert(entity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 修改系统规则
    * @Date 19:53 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateSystemRule(YwuSystemRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuSystemRuleEntity search = new YwuSystemRuleEntity();
        search.setId(ruleDto.getId());
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        YwuSystemRuleEntity queryEntity = systemRuleRepository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setApp(queryEntity.getApp());
        // 调用接口进行修改
        doRestTemplate(ruleDto.getApp(), SYSTEM_RULE_UPDATE_URL, ruleDto);
        // 修改数据
        YwuSystemRuleEntity update = new YwuSystemRuleEntity();
        BeanUtils.copyProperties(ruleDto, update);
        update.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        systemRuleRepository.update(update);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除系统规则
    * @Date 19:53 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> deleteSystemRule(YwuSystemRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 查询是否有修改权限
        YwuSystemRuleEntity search = new YwuSystemRuleEntity();
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        search.setId(ruleDto.getId());
        YwuSystemRuleEntity queryEntity = systemRuleRepository.getEntity(search);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id is not exist");
        }
        ruleDto.setType(queryEntity.getType());
        ruleDto.setApp(queryEntity.getApp());
        // 调用微服务删除流控规则
        doRestTemplate(ruleDto.getApp(), SYSTEM_RULE_DELETE_URL, ruleDto);
        // 删除数据
        YwuSystemRuleEntity delete = new YwuSystemRuleEntity();
        delete.setId(ruleDto.getId());
        systemRuleRepository.delete(delete);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 分页查询
    * @Date 19:53 2025/4/15
    * @Param [ruleDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> querySystemRulePageList(YwuSystemRuleDto ruleDto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        ruleDto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        PageService.execPageStartAndEnd(ruleDto.getPageInfo());
        PageList<YwuSystemRuleEntity> pageListRes = new PageList<>();
        pageListRes.setPageSize(ruleDto.getPageInfo().getPageSize());
        pageListRes.setPageIndex(ruleDto.getPageInfo().getPageIndex());
        // 查询数量
        int count = systemRuleRepository.queryListCount(ruleDto);
        pageListRes.setRecordCount(count);
        if (count == 0) {
            log.debug("querySystemRulePageList empty");
            pageListRes.setDataList(new ArrayList<>());
            return CommonResult.success(pageListRes);
        }
        // 查询列表
        List<YwuSystemRuleEntity> ywuFlowRuleEntities = systemRuleRepository.queryPageList(ruleDto);
        pageListRes.setDataList(ywuFlowRuleEntities);
        return CommonResult.success(pageListRes);
    }
}
